package cn.tedu._05mvcboot03.controller;

import cn.tedu._05mvcboot03.common.response.JsonResult;
import cn.tedu._05mvcboot03.common.response.StatusCode;
import cn.tedu._05mvcboot03.mapper.UserMapper;
import cn.tedu._05mvcboot03.pojo.dto.UserArticleDTO;
import cn.tedu._05mvcboot03.pojo.dto.UserLoginDTO;
import cn.tedu._05mvcboot03.pojo.entity.Article;
import cn.tedu._05mvcboot03.pojo.vo.ArticleVO;
import cn.tedu._05mvcboot03.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

@Api(tags = "01用户模块")
@Slf4j//打印日制
@Validated
@RestController
@RequestMapping("/v1/users/")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @ApiOperation("登录功能")
    @PostMapping("login")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO,@ApiIgnore HttpSession session){
        log.debug("userLoginDTO="+userLoginDTO);
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();
        //调用接口
        UserVO userVO = userMapper.selectUser(username,password);
        //判断
        if(userVO==null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        //登录成功，建立会话
        session.setAttribute("user",userVO);
        return JsonResult.ok();
    }

    @ApiOperation("发表文章")
    @PostMapping("article")
    public JsonResult article(@RequestBody @Validated UserArticleDTO userArticleDTO, @ApiIgnore HttpSession session){
        log.debug("userArticleDTO="+userArticleDTO);
        UserVO userVO = (UserVO) session.getAttribute("user");
        if(userVO==null){
            return new JsonResult(StatusCode.NOT_LOGIN);
        }
        Article article = new Article();
        BeanUtils.copyProperties(userArticleDTO,article);
        article.setUserId(userVO.getId());
        userMapper.insertArticle(article);
        return JsonResult.ok();
    }

    @ApiOperation("查询文章")
    @GetMapping("selectArticleById")
    public JsonResult selectArticleById(@Range(min=1,max=100,message="文章内容在1~100之间") @RequestParam Long id){
        log.debug("id"+id);
        ArticleVO articleVO = userMapper.selectArticleById(id);
        log.debug("articleVO"+articleVO);
        return JsonResult.ok(articleVO);
    }
}
